from QQLoginTool.QQtool import OAuthQQ

# Create your views here.
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

import constants
from oauth import serializers
from oauth.models import OAuthQQUser
from oauth.utils import generate_save_user_token
from users.utils import generate_jwt_token, merge_cookie_cart


class QQAuthURLView(APIView):

    def get(self, request):

        next_url = request.query_params.get('next', '/')

        # 获取QQ登录页面网址
        oauth = OAuthQQ(client_id=constants.QQ_CLIENT_ID, client_secret=constants.QQ_CLIENT_SECRET,
                        redirect_uri=constants.QQ_REDIRECT_URI, state=next_url)
        login_url = oauth.get_qq_url()

        return Response({'login_url': login_url})


class QQAuthUserView(CreateAPIView):
    serializer_class = serializers.QQAuthUserSerializer

    def get(self, request):

        # 获取前端的Code数据
        code = request.query_params.get('code', None)

        # 获取QQ登录页面网址
        oauth = OAuthQQ(client_id=constants.QQ_CLIENT_ID, client_secret=constants.QQ_CLIENT_SECRET,
                        redirect_uri=constants.QQ_REDIRECT_URI)

        # 根据code向QQ服务器获取access_token和openid
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            return Response({'message':'QQ服务器异常'}, status=503)

        # 根据openid 从数据库中查找qquser，看当前的openid是否有绑定用户
        try:
            qquser = OAuthQQUser.objects.get(open_id=openid)
        except Exception as e:
            # 如果没有绑定，则返回一个加密后的openid，前端收到数据后检查数据中是否有user_id，如果没有则认为没有绑定，跳转到绑定页面
            access_token = generate_save_user_token(openid)
            return Response({'access_token': access_token})
        else:
            # 如果有用户，则返回一个token和user_id、username
            user = qquser.user
            token = generate_jwt_token(user)

            data = {
                'user_id': user.id,
                'username': user.username,
                'token': token
            }

            response = Response(data)
            # 合并购物车
            response = merge_cookie_cart(request, user, response)
            return response

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        user = self.user
        if user.is_authenticated:
            # 合并购物车
            response = merge_cookie_cart(request, user, response)

        return response



